package 贪心策略;

import org.omg.CORBA.INTERNAL;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 三数之和15 {

    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>>ans = new ArrayList<>();
        int n = nums.length;
        if(nums[n-1]<0||n<3)return ans;
        for(int i=0;i<n-2;i++){
            if(nums[i]>0)break;
            if (i!=0&&nums[i]==nums[i-1])continue;
            int l = i + 1;
            int r = n-1;
            while (l<r){
                int sum = nums[i]+nums[l]+nums[r];
                if(sum==0){
                    ans.add(Arrays.asList(nums[i],nums[l],nums[r]));
                    while(l<r && nums[l]==nums[l+1])
                        l++;
                    while(l<r && nums[r]==nums[r-1])
                        r--;
                    l++;
                    r--;
                }else if(sum>0){
                    r--;
                }else{
                    l++;
                }
            }

        }
        return ans;
    }
}
